<template>
  <div class="app-container">
    <h3>组卷信息</h3>
    <el-card style="margin-top: 20px">
      <div style="float: right; font-weight: bold; color: #ff0000">
        试卷总分：{{ examDto.totalScore }}分
      </div>

      <div>
        <el-button
          class="filter-item"
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          添加题库
        </el-button>

        <el-table
          :data="examDto.examRepos"
          :border="false"
          empty-text="请点击上面的`添加题库`进行设置"
          style="width: 100%; margin-top: 15px"
        >
          <el-table-column label="题库" width="200">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.repoId"
                placeholder="请选择"
                @change="repoChange(scope.row)"
              >
                <el-option
                  v-for="item in repoList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="单选数量" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.radioCount"
                :min="0"
                :max="scope.row.totalRadio"
                :controls="false"
                style="width: 60%"
              />
              / {{ scope.row.totalRadio }}
            </template>
          </el-table-column>

          <el-table-column label="单选分数" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.radioScore"
                :min="0"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </el-table-column>

          <el-table-column label="多选数量" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.multiCount"
                :min="0"
                :max="scope.row.totalMulti"
                :controls="false"
                style="width: 60%"
              />
              / {{ scope.row.totalMulti }}
            </template>
          </el-table-column>

          <el-table-column label="多选分数" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.multiScore"
                :min="0"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </el-table-column>

          <el-table-column label="判断题数量" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.judgeCount"
                :min="0"
                :max="scope.row.totalJudge"
                :controls="false"
                style="width: 60%"
              />
              / {{ scope.row.totalJudge }}
            </template>
          </el-table-column>

          <el-table-column label="判断题分数" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.judgeScore"
                :min="0"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </el-table-column>

          <el-table-column label="简答题数量" align="center">
            <template slot-scope="scope">
              <el-input-number
                style="width: 60%"
                v-model="scope.row.jdtCount"
                :max="scope.row.totalJdt"
                :min="0"
                :controls="false"
              />
              / {{ scope.row.totalJdt }}
            </template>
          </el-table-column>

          <el-table-column label="简答题分数" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.jdtScore"
                :min="0"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </el-table-column>

          <el-table-column label="删除" align="center" width="80px">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeItem(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <h3>考试配置</h3>
    <el-card style="margin-top: 20px">
      <el-form
        ref="examDto"
        :model="examDto"
        :rules="rules"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="考试名称" prop="title">
          <el-input v-model="examDto.title" />
        </el-form-item>

        <el-form-item label="考试描述" prop="content">
          <el-input v-model="examDto.content" type="textarea" />
        </el-form-item>

        <el-form-item label="总分数" prop="totalScore">
          <el-input-number :value="examDto.totalScore" disabled />
        </el-form-item>

        <el-form-item label="及格分" prop="qualifyScore">
          <el-input-number
            v-model="examDto.qualifyScore"
            :max="examDto.totalScore"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="考试时长(分钟)" prop="totalTime">
          <el-input-number v-model="examDto.totalTime" />
        </el-form-item>

        <el-form-item label="是否限时">
          <el-checkbox v-model="examDto.timeLimit" />
        </el-form-item>

        <el-form-item
          v-if="examDto.timeLimit"
          label="考试时间"
          prop="totalTime"
        >
          <el-date-picker
            v-model="dateValues"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </el-card>

    <h3>权限配置</h3>
    <el-card style="margin-top: 20px">
      <el-radio-group
        v-model="examDto.openType"
        @change="
          examDto.checkedUsers = [];
          examDto.departIds = [];
        "
        style="margin-bottom: 20px"
      >
        <el-radio :label="1" border>完全公开</el-radio>
        <el-radio :label="2" border>部门开放</el-radio>
        <el-radio :label="3" border>指定人员</el-radio>
      </el-radio-group>

      <el-alert
        v-if="examDto.openType === 1"
        title="开放的，任何人都可以进行考试！"
        type="warning"
      />

      <div v-if="examDto.openType === 2">
        <el-tree
          ref="tree"
          empty-text=" "
          :data="treeData"
          default-expand-all
          show-checkbox
          node-key="id"
          :default-checked-keys="examDto.departIds"
          @check-change="handleCheckChange"
        />
      </div>

      <div v-if="examDto.openType === 3">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          >全选</el-checkbox
        >
        <div style="margin: 15px 0"></div>
        <el-checkbox-group
          v-model="examDto.checkedUsers"
          @change="handleCheckedCitiesChange"
        >
          <el-checkbox v-for="user in users" :label="user.userId" :key="user">
            {{ user.nickName }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </el-card>

    <div style="margin-top: 20px">
      <el-button type="primary" @click="handleSave('examDto')">保存</el-button>
    </div>
  </div>
</template>
<script>
import { examData } from "@/api/exam";
import { findAll } from "@/api/repo";
import { findDepartAll } from "@/api/depart";
import { findUserAll } from "@/api/user";
import { updateExam } from "@/api/exam";
export default {
  data() {
    //自定义表单校验规则
    var checkQualifyScore = (rule, value, callback) => {
      if (value == null || value > this.examDto.totalScore || value < 0) {
        return callback(new Error("及格分不合法"));
      } else {
        callback();
      }
    };

    return {
      treeData: [], //部门数据
      dateValues: [],
      repoList: [],
      examDto: {
        id: "",
        examRepos: [],
        departIds: [],
        timeLimit: false,
        openType: 1,
        title: "",
        content: "",
        startTime: "",
        endTime: "",
        // 选中的考试人员
        checkedUsers: [],
      },
      rules: {
        qualifyScore: [
          { validator: checkQualifyScore, trigger: ["blur", "change"] },
        ],
      },

      // 人员信息回显
      checkAll: false,
      users: [],
      isIndeterminate: true,
    };
  },
  watch: {
    "examDto.examRepos": {
      handler(newVal, oldVal) {
        var totalScore = 0;
        newVal.forEach((item) => {
          console.log(item.radioCount * item.radioScore);
          totalScore += item.radioCount * item.radioScore;
          totalScore += item.multiCount * item.multiScore;
          totalScore += item.judgeCount * item.judgeScore;
          totalScore += item.jdtCount * item.jdtScore;
        });
        this.examDto.totalScore = totalScore;

        //强制刷新视图
        this.$forceUpdate();
      },
      // 监听器只能监听到数组个数发送变化，深度监听才能监听到数组中每个对象的属性的变化
      deep: true,
    },
    dateValues: {
      handler() {
        this.examDto.startTime = this.dateValues[0];
        this.examDto.endTime = this.dateValues[1];
      },
    },
  },
  methods: {
    handleCheckChange(a, b, c) {
      var nodes = this.$refs.tree.getCheckedNodes();
      console.log(nodes);
      var departIds = [];
      nodes.forEach((node) => {
        departIds.push(node.id);
      });

      this.examDto.departIds = departIds;
    },
    handleAdd() {
      this.examDto.examRepos.push({
        repoId: "",
        radioCount: 0,
        radioScore: 0,
        multiCount: 0,
        multiScore: 0,
        judgeCount: 0,
        judgeScore: 0,
        jdtCount: 0,
        jdtScore: 0,
      });
    },
    removeItem(index) {
      this.examDto.examRepos.splice(index, 1);
    },
    findRepoList() {
      findAll().then((res) => {
        this.repoList = res;
      });
    },
    findDepart() {
      findDepartAll().then((res) => {
        this.treeData = res;
      });
    },
    findUser() {
      findUserAll().then((res) => {
        this.users = res;
      });
    },

    addtotalCount() {
      this.examDto.examRepos.forEach((item) => {
        var repoEntity = {};
        this.repoList.forEach((repo) => {
          if (repo.id == item.repoId) {
            repoEntity = repo;
          }
        });
        item.totalRadio = repoEntity.radioCount;
        item.totalMulti = repoEntity.multiCount;
        item.totalJudge = repoEntity.judgeCount;
        item.totalJdt = repoEntity.jdtCount;
      });
    },
    repoChange(item) {
      var repoEntity = {};
      this.repoList.forEach((repo) => {
        if (repo.id == item.repoId) {
          repoEntity = repo;
        }
      });

      item.totalRadio = repoEntity.radioCount;
      item.totalMulti = repoEntity.multiCount;
      item.totalJudge = repoEntity.judgeCount;
      item.totalJdt = repoEntity.jdtCount;
    },
    // 人员信息回显函数
    handleCheckAllChange(val) {
      // val全选为true，取消全选为false
      if (val) {
        this.users.forEach((item) => {
          this.examDto.checkedUsers.push(item.userId);
        });
      } else {
        this.examDto.checkedUsers = [];
      }
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.users.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.users.length;
    },

    // 提交试卷时表单校验
    handleSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.examDto.timeLimit = this.examDto.timeLimit ? 1 : 0;
          updateExam(this.examDto).then((res) => {
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
              });
              this.$router.push({ path: "/exam/list" });
            } else {
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  created() {
    //查询题库列表
    this.findRepoList();

    // 获取部门数据
    this.findDepart();

    // 获取人员信息
    this.findUser();

    // 页面加载完成发送axios请求获取试卷信息
    examData(this.$route.query.examId).then((res) => {
      var examInfo = res.data;
      // 获取题库信息
      this.examDto.examRepos = examInfo.examRepos;

      this.examDto.id = examInfo.exam.id;
      this.examDto.title = examInfo.exam.title;
      this.examDto.content = examInfo.exam.content;
      this.examDto.totalScore = examInfo.exam.totalScore;
      this.examDto.qualifyScore = examInfo.exam.qualifyScore;
      this.examDto.totalTime = examInfo.exam.totalTime;
      // 是否限时(0:不限时;1:限时)
      this.examDto.timeLimit = examInfo.exam.timeLimit == 0 ? false : true;
      // 考试开始时间与结束时间
      if (this.examDto.timeLimit) {
        this.dateValues.push(examInfo.exam.startTime);
        this.dateValues.push(examInfo.exam.endTime);
      }

      // 考试权限
      this.examDto.openType = examInfo.exam.openType;

      if (examInfo.exam.openType == 2) {
        // 部门信息回显
        examInfo.examDeparts.forEach((item) => {
          this.examDto.departIds.push(item.departId);
        });
      }
      if (examInfo.exam.openType == 3) {
        // 人员信息回显
        examInfo.examUsers.forEach((item) => {
          this.examDto.checkedUsers.push(parseInt(item.userId));
        });
      }

      this.addtotalCount();
    });
  },
};
</script>